package com.example.demo.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;

        try {
            //创建服务端
            serverSocket = new ServerSocket(8888);
            System.out.println("服务端已启动，等待客户端连接...");

            while (true) {
                // 监听客户端请求，接收不到请求会一直等待
                clientSocket = serverSocket.accept();
                int port = clientSocket.getPort();
                InetAddress inetAddress = clientSocket.getInetAddress();
                System.out.println("客户端 " + inetAddress + ":" + port + " 连接成功！");
                //处理客户端消息
                new Thread(new ServerThread(clientSocket)).start();
            }
        } catch (IOException e) {
            System.out.println("客户端连接失败：" + e.getMessage());
        } finally {
            try {
                if (clientSocket != null) {
                    clientSocket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                System.out.println("关闭资源失败：" + e.getMessage());
            }
        }
    }

    static class ServerThread implements Runnable {

        private Socket clientSocket;

        public ServerThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            //获取客户端输入流以便接收客户端数据
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                //获取客户端输出流以便向客户端发送数据
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream());

                int port = clientSocket.getPort();
                InetAddress inetAddress = clientSocket.getInetAddress();
                String address = inetAddress + ":" + port;

                String inputLine;
                //没有接收到数据，read会一直阻塞
                while ((inputLine = in.readLine()) != null) {
                    //接收客户端消息
                    System.out.println("客户端" + address + "发来消息：" + inputLine);
                    //给客户端发送消息
                    out.println("服务端已接收到消息并回复：" + inputLine);
                    out.flush();
                }

                System.out.println("aaaaaaaaaaaaaaaaaa");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
